<template>
  <div class="app-container">
    <div class="header">
      <h2>离线地图演示</h2>
      <p>点击地图查看位置信息，点击两个点绘制飞行轨迹</p>
      <div class="info-panel" v-if="clickInfo">
        点击位置: {{ clickInfo }}
      </div>
      <div class="control-info">
        <el-button @click="startFlight" type="primary" size="small" :disabled="points.length !== 2">开始飞行</el-button>
        <el-button @click="pauseFlight" type="warning" size="small" :disabled="!isFlying">暂停飞行</el-button>
        <el-button @click="resetFlight" type="info" size="small">重置飞行</el-button>
      </div>
    </div>

    <!-- 地图容器 -->
    <div id="mapContainer" class="map-container"></div>

    <!-- 控制面板 -->
    <div class="control-panel">
      <el-button @click="clearAll" type="danger" size="small">清除所有</el-button>
      <span class="point-count">已选择点位: {{ points.length }}</span>
      <span class="flight-status" v-if="isFlying">🛫 飞行中...</span>
      <span class="flight-status" v-else-if="flightCompleted">✅ 飞行完成</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'OfflineMap',
  data() {
    return {
      map: null,
      points: [],           // 存储点击的点位
      clickInfo: '',        // 点击位置信息
      markers: [],          // 标记点数组
      polyline: null,       // 轨迹线
      movingMarker: null,   // 移动标记
      isFlying: false,      // 飞行状态
      flightCompleted: false // 飞行完成状态
    }
  },
  mounted() {
    // 先加载插件，然后初始化地图
    this.loadPlugins().then(() => {
      this.$nextTick(() => {
        this.initMap();
      });
    });
  },
  beforeDestroy() {
    // 组件销毁时清理地图
    if (this.map) {
      this.map.remove();
    }
    if (this.movingMarker) {
      this.movingMarker.stop();
    }
  },
  methods: {
    // 加载本地插件
    loadPlugins() {
      return new Promise((resolve, reject) => {
        // 动态创建script标签加载插件
        const scripts = [
          '/leaflet/plugins/MovingMarker/Leaflet.MovingMarker.js',
          '/leaflet/plugins/Polyline.SnakeAnim/Leaflet.Polyline.SnakeAnim.js'
        ];

        let loadedCount = 0;

        scripts.forEach(scriptSrc => {
          const script = document.createElement('script');
          script.src = scriptSrc;
          script.onload = () => {
            loadedCount++;
            if (loadedCount === scripts.length) {
              console.log('所有插件加载完成');
              resolve();
            }
          };
          script.onerror = () => {
            console.error(`插件加载失败: ${scriptSrc}`);
            loadedCount++;
            if (loadedCount === scripts.length) {
              resolve(); // 即使有插件加载失败也继续
            }
          };
          document.head.appendChild(script);
        });
      });
    },

    initMap() {
      console.log('正在初始化地图...');

      try {
        // 初始化地图，设置初始视图
        this.map = L.map('mapContainer').setView([40.0, 123.0], 12);

        console.log('地图对象创建成功:', this.map);

        // 添加离线瓦片图层
        L.tileLayer('/tiles/{z}/{x}/{y}.png', {
          maxZoom: 12,
          minZoom: 8,
          attribution: '离线地图 - 若依框架',
          noWrap: true
        }).addTo(this.map);

        console.log('瓦片图层已添加');

        // 绑定地图点击事件
        this.map.on('click', this.onMapClick);
        console.log('点击事件绑定成功');

        // 检查地图容器和瓦片
        this.checkMapStatus();

      } catch (error) {
        console.error('地图初始化失败:', error);
        this.$message.error('地图初始化失败: ' + error.message);
      }
    },

    // 检查地图状态
    checkMapStatus() {
      setTimeout(() => {
        const container = document.getElementById('mapContainer');
        if (container) {
          console.log('地图容器尺寸:', container.offsetWidth, 'x', container.offsetHeight);
        }

        // 检查是否有瓦片加载
        const tiles = document.querySelectorAll('.leaflet-tile-loaded');
        console.log('已加载瓦片数量:', tiles.length);

        if (tiles.length === 0) {
          console.warn('没有瓦片被加载，请检查瓦片路径和网络请求');
        }
      }, 1000);
    },

    // 地图点击事件处理
    onMapClick(e) {
      const latlng = e.latlng;
      const lat = latlng.lat.toFixed(6);
      const lng = latlng.lng.toFixed(6);

      this.clickInfo = `纬度: ${lat}, 经度: ${lng}`;
      console.log('地图点击位置:', this.clickInfo);

      // 显示点击位置信息
      L.popup()
        .setLatLng(latlng)
        .setContent(`
          <div style="text-align: center;">
            <strong>点击位置</strong><br>
            纬度: ${lat}<br>
            经度: ${lng}<br>
            <small>点位 ${this.points.length + 1}</small>
          </div>
        `)
        .openOn(this.map);

      // 添加标记点
      const marker = this.createPointMarker(latlng, this.points.length + 1);
      this.markers.push(marker);
      this.points.push(latlng);

      // 如果收集了两个点，自动绘制轨迹
      if (this.points.length === 2) {
        this.drawFlightRoute();
      }
    },

    // 创建点标记
    createPointMarker(latlng, number) {
      const isStart = number === 1;
      const color = isStart ? '#52c41a' : '#f5222d';
      const text = isStart ? '起' : '终';

      const icon = L.divIcon({
        html: `
          <div style="
            background: ${color};
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 12px;
            border: 3px solid white;
            box-shadow: 0 2px 6px rgba(0,0,0,0.3);
          ">${text}</div>
        `,
        className: `point-marker ${isStart ? 'start-marker' : 'end-marker'}`,
        iconSize: [24, 24],
        iconAnchor: [12, 12]
      });

      return L.marker(latlng, { icon: icon })
        .addTo(this.map)
        .bindPopup(`点位 ${number}: [${latlng.lat.toFixed(4)}, ${latlng.lng.toFixed(4)}]`);
    },

    // 绘制飞行轨迹
    drawFlightRoute() {
      // 清除之前的轨迹线和标记
      this.clearFlightElements();

      if (this.points.length < 2) return;

      // 创建轨迹线
      this.polyline = L.polyline(this.points, {
        color: '#1890ff',
        weight: 4,
        opacity: 0.7,
        dashArray: '10, 5',
        lineJoin: 'round'
      }).addTo(this.map);

      // 直接调用 createMovingMarker 方法
      this.createMovingMarker();

      // 自动调整地图视图
      const bounds = L.latLngBounds(this.points);
      this.map.fitBounds(bounds, { padding: [50, 50] });

      this.$message.success('轨迹已绘制，点击"开始飞行"按钮启动飞行！');
    },

    createMovingMarker() {
      console.log('创建移动标记，检查插件可用性...');

      // 先检查插件是否可用
      if (typeof L.Marker.movingMarker === 'function' || typeof L.Marker.MovingMarker === 'function') {
        console.log('✅ 移动标记插件可用');

        try {
          // 创建飞机图标
          const planeIcon = this.createPlaneIcon();

          let markerInstance;

          // 优先使用工厂函数
          if (typeof L.Marker.movingMarker === 'function') {
            console.log('使用工厂函数 L.Marker.movingMarker');
            markerInstance = L.Marker.movingMarker(
              this.points,
              [5000], // 5秒完成飞行
              {
                icon: planeIcon,
                autostart: false,
                loop: false
              }
            );
          }
          // 其次使用构造函数
          else if (typeof L.Marker.MovingMarker === 'function') {
            console.log('使用构造函数 L.Marker.MovingMarker');
            markerInstance = new L.Marker.MovingMarker(
              this.points,
              [5000], // 5秒完成飞行
              {
                icon: planeIcon,
                autostart: false,
                loop: false
              }
            );
          }

          // 添加到地图
          this.movingMarker = markerInstance.addTo(this.map);

          console.log('✅ 移动标记创建成功:', this.movingMarker);

          // 添加事件监听
          this.movingMarker.on('start', () => {
            console.log('飞行动画开始');
            this.isFlying = true;
            this.flightCompleted = false;
          });

          this.movingMarker.on('end', () => {
            console.log('飞行动画结束');
            this.isFlying = false;
            this.flightCompleted = true;
            this.$message.success('飞行完成！');
          });

        } catch (error) {
          console.error('❌ 创建移动标记时出错:', error);
          this.createStandaloneFlightAnimation(); // 使用独立实现
        }
      } else {
        console.warn('❌ 移动标记插件不可用，使用独立实现');
        this.createStandaloneFlightAnimation(); // 使用独立实现
      }
    },
    // 独立飞行动画实现
    createStandaloneFlightAnimation() {
      if (this.points.length < 2) return;

      console.log('使用独立飞行动画实现');

      // 清除之前的动画
      this.stopFlightAnimation();

      const startPoint = this.points[0];
      const endPoint = this.points[1];
      const duration = 5000; // 5秒

      // 创建飞机图标
      const planeIcon = this.createPlaneIcon();
      this.movingMarker = L.marker(startPoint, {
        icon: planeIcon
      }).addTo(this.map);

      this.isFlying = true;
      this.flightCompleted = false;

      const startTime = Date.now();

      const animate = () => {
        if (!this.isFlying) return;

        const elapsed = Date.now() - startTime;
        const progress = Math.min(elapsed / duration, 1);

        // 计算当前位置（线性插值）
        const currentLat = startPoint.lat + (endPoint.lat - startPoint.lat) * progress;
        const currentLng = startPoint.lng + (endPoint.lng - startPoint.lng) * progress;

        // 更新标记位置
        this.movingMarker.setLatLng([currentLat, currentLng]);

        // 计算并更新方向
        this.updateMarkerDirection([currentLat, currentLng], progress);

        if (progress < 1) {
          this.animationFrame = requestAnimationFrame(animate);
        } else {
          this.isFlying = false;
          this.flightCompleted = true;
          this.$message.success('飞行完成！');
        }
      };

      this.animationFrame = requestAnimationFrame(animate);
      this.$message.info('飞行开始！');
    },
    // 创建飞机图标
    createPlaneIcon() {
      return L.divIcon({
        html: `
      <div style="
        background: #1890ff;
        border-radius: 50%;
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 3px solid white;
        box-shadow: 0 2px 8px rgba(0,0,0,0.3);
      ">
        <div style="
          color: white;
          font-size: 14px;
          font-weight: bold;
        ">✈</div>
      </div>
    `,
        className: 'moving-marker',
        iconSize: [32, 32],
        iconAnchor: [16, 16]
      });
    },

// 更新标记方向
    updateMarkerDirection(currentPos, progress) {
      if (progress >= 0.99) return;

      const nextProgress = Math.min(progress + 0.02, 1);
      const nextLat = this.points[0].lat + (this.points[1].lat - this.points[0].lat) * nextProgress;
      const nextLng = this.points[0].lng + (this.points[1].lng - this.points[0].lng) * nextProgress;

      // 计算角度（弧度）
      const angle = Math.atan2(nextLng - currentPos[1], nextLat - currentPos[0]);
      // 转换为度数并调整（让0度指向右边，像CSS那样）
      const degrees = angle * (180 / Math.PI) + 90;

      // 更新标记旋转
      const markerElement = this.movingMarker.getElement();
      if (markerElement) {
        markerElement.style.transform = `rotate(${degrees}deg)`;
        markerElement.style.transition = 'transform 0.1s ease-out';
      }
    },

// 停止飞行动画
    stopFlightAnimation() {
      if (this.animationFrame) {
        cancelAnimationFrame(this.animationFrame);
        this.animationFrame = null;
      }
      this.isFlying = false;

      if (this.movingMarker) {
        this.map.removeLayer(this.movingMarker);
        this.movingMarker = null;
      }
    },

    // 备用移动标记方案
    createFallbackMovingMarker() {
      const planeIcon = L.divIcon({
        html: '✈',
        className: 'fallback-moving-marker',
        iconSize: [20, 20],
        iconAnchor: [10, 10]
      });

      this.movingMarker = L.marker(this.points[0], { icon: planeIcon }).addTo(this.map);
    },

    // 开始飞行
    startFlight() {
      if (this.points.length < 2) {
        this.$message.warning('请先选择两个点');
        return;
      }

      // 如果使用插件且有 start 方法
      if (this.movingMarker && typeof this.movingMarker.start === 'function') {
        this.movingMarker.start();
        this.$message.info('飞行开始！');
      }
      // 如果使用独立动画
      else if (!this.isFlying) {
        this.createStandaloneFlightAnimation();
      }
    },

// 暂停飞行
    pauseFlight() {
      // 如果使用插件且有 pause 方法
      if (this.movingMarker && typeof this.movingMarker.pause === 'function') {
        this.movingMarker.pause();
        this.isFlying = false;
        this.$message.info('飞行已暂停');
      }
      // 如果使用独立动画
      else {
        this.isFlying = false;
        this.$message.info('飞行已暂停');
      }
    },

    // 重置飞行
    resetFlight() {
      this.clearFlightElements();
      this.isFlying = false;
      this.flightCompleted = false;

      // 重新绘制轨迹
      if (this.points.length >= 2) {
        this.drawFlightRoute();
      }

      this.$message.info('飞行已重置');
    },

    // 清除飞行相关元素
    clearFlightElements() {
      if (this.polyline) {
        this.map.removeLayer(this.polyline);
        this.polyline = null;
      }

      // 停止独立动画
      this.stopFlightAnimation();

      // 停止插件动画
      if (this.movingMarker && typeof this.movingMarker.stop === 'function') {
        this.movingMarker.stop();
        this.map.removeLayer(this.movingMarker);
        this.movingMarker = null;
      }

      this.isFlying = false;
      this.flightCompleted = false;
    },

    // 清除所有
    clearAll() {
      // 清除标记点
      this.markers.forEach(marker => {
        this.map.removeLayer(marker);
      });
      this.markers = [];

      // 清除飞行元素
      this.clearFlightElements();

      // 清除数据
      this.points = [];
      this.clickInfo = '';

      this.$message.info('已清除所有标记和轨迹');
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  text-align: center;
}

.info-panel {
  background: #f0f9ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  padding: 10px;
  margin: 10px 0;
}

.control-info {
  margin: 15px 0;
}

.control-info .el-button {
  margin: 0 5px;
}

.map-container {
  height: 600px;
  width: 100%;
  border: 2px solid #dcdfe6;
  border-radius: 8px;
}

.control-panel {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.point-count {
  color: #409eff;
  font-weight: bold;
}

.flight-status {
  color: #67c23a;
  font-weight: bold;
}
</style>

<style>
/* 全局Leaflet样式修正 */
.leaflet-container {
  background: #f8f9fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 移动标记样式 */
.moving-marker {
  z-index: 1000;
}

.fallback-moving-marker {
  background: #1890ff;
  color: white;
  border-radius: 50%;
  text-align: center;
  font-weight: bold;
  border: 2px solid white;
  box-shadow: 0 2px 6px rgba(0,0,0,0.3);
}

/* 点标记动画 */
.point-marker {
  transition: transform 0.3s ease;
}

.point-marker:hover {
  transform: scale(1.1);
}
</style>
